<?php

class ServiceController extends St_Controller_Action_Admin {

    public function ajaxuploadAction() {
        Zend_Loader::loadClass("St_Media");
        $path_folder = $this->_getParam('pathFolder', 'public');
        $path = realpath(APPLICATION_PATH . '/../../uploads/'.$path_folder.'/');
        $clickedID = $_POST['data']; // Acts as the name
        $thumbnail_width = $this->_getParam('thumbnail_width', false);
        
        $filename = $_FILES[$clickedID];
        $file_name = $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);
        $filename['name'] = str_replace('.', time() . '.', $filename['name']);
        $_FILES[$clickedID]['name'] = $filename['name'];
        
        $type = $_FILES[$clickedID]['type'];
        $type = explode('/', $type);
        $allowType = array('jpeg', 'png', 'gif', 'jpg');
//        echo in_array($type[1], $allowType).'aaa';
//        var_dump($type);
        if ($type[0] == 'image' && in_array($type[1], $allowType)) {
            $upload = new Zend_File_Transfer_Adapter_Http();            
            $upload->setDestination($path);
            
            try {
                $upload->receive();
            } catch (Zend_File_Transfer_Exception $e) {
                throw new Exception('Bad image data: ' . $e->getMessage());
            }
            if ($upload->isUploaded()) {
                $source = $upload->getFileName();
                $media = new St_Media();
                list($width, $height) = getimagesize($source);
                if ($width > $thumbnail_width && $thumbnail_width) {
                    $max_w = $thumbnail_width;
                    $max_h = round(($max_w * $height) / $width);
                    $thumbnail = $media->image_resize($source, $max_w, $max_h, true, 'thumb');
                } else {
                    $thumbnail = $source;
                }
                
                $baseUrl = St_Registry::getConfig("base_url");
                $imgUrl = $baseUrl . 'uploads/'.$path_folder.'/' . basename($source);
                $thumbUrl = $baseUrl . 'uploads/'.$path_folder.'/' . basename($thumbnail);
            }

            echo $imgUrl . '|*|' . $thumbUrl;
        }else{
            echo $imgUrl . '|*|' . $thumbUrl;
        }
        if ($_POST['ajax'])
            die;
    }

    public function ajaxremoveAction() {
        $path_folder = $this->_getParam('pathFolder', 'public');
        $path = realpath(APPLICATION_PATH . '/../../uploads/'.$path_folder.'/');
        $file = $_POST['file']; // Acts as the name
        $img_name = basename($file);
        $thumb_name = str_replace('.', '-thumb.', $img_name);
        $img_file = $path . DIRECTORY_SEPARATOR . $img_name;
        $thumb_file = $path . DIRECTORY_SEPARATOR . $thumb_name;
        unlink($img_file);
        @unlink($thumb_file);
        if ($_POST['ajax'])
            die;
    }

}

